<?php
namespace Home\Controller;

use Think\Upload;
use Think\Controller;

class IndexController extends Controller
{
    public function index()
    {
//        $obj = M("shouye");
//        $arr = $obj->where("type=1")->select();
//        $this->assign('arr',$arr);
        $this->display();
    }

    public function maxDetail()
    {
        $this->display("maxDetail");
    }

    public function maxDetail2()
    {
        $this->display("maxDetail2");
    }

    public function maxDetail3()
    {
        $this->display("maxDetail3");
    }

    public function maxDetail4()
    {
        $this->display("maxDetail4");
    }

    //列表详情页
    public function listDetail($type)
    {
        if ($type ==1){
            $arr['name'] = '孕妇建卡';
            $arr['intro'] = 'xxxxxxxxx';
            $arr['price'] = 500;
            $arr['type'] = 1;
        }elseif ($type ==2){
            $arr['name'] = '孕妇体检';
            $arr['intro'] = 'xxxxxxxxx';
            $arr['price'] = 200;
            $arr['type'] =2;
        }elseif ($type == 3){
            $arr['name'] = '产前入院';
            $arr['intro'] = 'xxxxxxxxx';
            $arr['price'] = 500;
            $arr['type'] =3;
        }else{
            $arr['name'] = '儿童挂号';
            $arr['intro'] = 'xxxxxxxxx';
            $arr['price'] = 500;
            $arr['type'] =4;
        }
        $this->assign("info", $arr);
        $this->display();
    }

    //保存孕妇预约
    public function womenyu(){
        $_REQUEST['create_time'] = time();
        $yu = M("yuyue_records");
        $res = $yu->add($_REQUEST);
        if($res){
            $data['code'] = 0;//成功
            $this->ajaxReturn($data);
        }
        $data['code'] = 1;//失败
        $this->ajaxReturn($data);

    }

    //医院列表
    public function hospitalList()
    {
        $obj = M("hospital");
        $datas = $obj->where("type=2")->select();
        $arr = [];
        foreach ($datas as $da){
            $da['desc'] = mb_substr($da['desc'],0,20,'utf-8')."...";
            $arr[] = $da;
        }
        $this->assign('datas',$arr);
        $this->display();
    }
    //名医主刀医院列表
    public function minghospitalList(){
        $obj = M("hospital");
        $datas = $obj->where("type=1")->select();
        $arr = [];
        foreach ($datas as $da){
            $da['desc'] = mb_substr($da['desc'],0,20,'utf-8')."...";
            $arr[] = $da;
        }
        $this->assign('datas',$arr);
        $this->display("minghospitalList");
    }

    //名医医院详情
    public function hospitalDetail($id){
        $obj = M("hospital");
        $datas = $obj->where("hid=".$id)->find();

        $datas['ta']=[];
        if(isset($datas['tabel'])){
            $datas['ta'] = array_filter(explode(",",$datas['tabel']));
        }

        $this->assign('ta',$datas['ta']);
        $this->assign('da',$datas);
        $this->display("fu-you");
    }

    //孕产发现
    public function womenFind(){
        $obj = M("shouye");
        $arr = $obj->where('type=3')->select();
        $this->assign('datas',$arr);
        $this->display();
    }
    //孕产故事
    public function womenStory(){
        $obj = M("shouye");
        $arr = $obj->where('type=4')->select();
        $this->assign('datas',$arr);
        $this->display();
    }
    //名医主刀发现
    public function mingFind(){
        $obj = M("shouye");
        $arr = $obj->where('type=3')->select();
        $this->assign('datas',$arr);
        $this->display("mingFind");
    }
    //名医主刀故事
    public function mingStory(){
        $obj = M("shouye");
        $arr = $obj->where('type=4')->select();
        $this->assign('datas',$arr);
        $this->display("mingStory");
    }

    //科室医院列表
    public function depart($id)
    {
        $obj = M("doctor");
        $arr = $obj->field('hospital')->where("dept_id=".$id)->group('hospital')->select();
        $docs = [];
        foreach ($arr as $a){
            $doc_arr = $obj->where("dept_id=".$id." and hospital='".$a['hospital']."'")->select();
            $doc_arr2= [];
            foreach ($doc_arr as $do){
                if(substr($do['img'],0,4) == "http"){
                    $do['sta'] = 1;
                }else{
                    $do['sta'] =2;
                }
                $doc_arr2[] = $do;
            }
            $a['docs'] = $doc_arr2;
            $docs[] = $a;
        }
        switch ($id){
            case 1:
                $str = "骨外科";
                break;
            case 2:
                $str = "神经外科";
                break;
            case 3:
                $str = "眼科";
                break;
            case 4:
                $str = "泌尿外科";
                break;
            case 5:
                $str = "整形外科";
                break;
            case 6:
                $str = "耳鼻喉科";
                break;
            case 7:
                $str = "胸外科";
                break;
            case 8:
                $str = "小儿外科";
                break;
            case 9:
                $str = "妇科";
                break;
            case 10:
                $str = "心血管科";
                break;
            case 11:
                $str = "颌面外科";
                break;
            case 12:
                $str = "普外科";
                break;
            default:
                $str = "骨外科";
        }
//        var_dump($docs);exit();

        $this->assign("datas",$docs);
        $this->assign("str",$str);
        $this->display("gu");
    }

    //名医主刀搜索
    public function search(){
        $this->display("funOld");
    }

    //名医主刀预约页面
    public function mingyuyue()
    {
        $phone = session('phone');
        if(!empty($phone)){
            $this->assign("phone",$phone);
        }else{
            $this->assign("phone",'');
        }
        $this->display();

    }

    public function fuyuyue()
    {
        $phone = session('phone');
        if(!empty($phone)){
            $this->assign("phone",$phone);
        }else{
            $this->assign("phone",'');
        }
        $this->display();

    }
    public function haiyuyue()
    {
        $phone = session('phone');
        if(!empty($phone)){
            $this->assign("phone",$phone);
        }else{
            $this->assign("phone",'');
        }
        $this->display();

    }

    //名医主刀预约功能
    public function mingyuyue2(){
        $mingyuyue = M("ming_yuyue");

        $_POST['create_time'] = time();
        $rs = $mingyuyue->add($_POST);
        if(!$rs){
            $data['code'] = 1;
            $data['msg'] = "失败";
            $this->ajaxReturn($data);
        }

        //预约成功发送短信
        $ill = $_POST['ill'];
        $sms_arr = ["单子","成功",$ill];
        sendTemplateSMS($_POST['phone'],$sms_arr,"169427");

        //通知王鹏
        $times = date('Y-m-d H:i',time());
        $smsContent = [$times.",手机号:".$_POST['phone'].",疾病:".$ill.",描述:".$_POST['desc']];
        sendTemplateSMS("18616655509",$smsContent,"201068");
        //注册用户或者登录
        $user = M("user");
        $rs = $user->where("phone=".$_POST['phone'])->find();
        if(empty($rs)){
            $arr['phone'] = $_POST['phone'];
            $arr['create_time'] = time();
            $user->add($arr);
        }
        session(["name"=>"phone","expire"=>604800]);
        session("phone",$_POST['phone']);

        $data['code'] = 0;
        $data['msg'] = "成功";
        $this->ajaxReturn($data);
    }

    //发布需求post
    public function addHelpPost()
    {
        $data = I('post.');
        $help = M("help_info");
//        追加一个元素
        $creatTime = date('Ymd-His', NOW_TIME);
        $imgTop = $data['name'] . 'help-' . $creatTime;
        $data['updated'] = NOW_TIME;

//            处理上传文件
        $upload = new Upload();
        $upload->maxSize = 5145728;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = './Public/helpImg/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        $upload->saveName = $imgTop;
        $upload->subName = '';
// 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        } else {// 上传成功 获取上传文件信息
            foreach ($info as $file) {
                $data['img'] = $file['savename'];
                //缩略图
                $image = new \Think\Image();
                $image->open("./Public/helpImg/" . $data['img']);
                $smallImgTop = $data['name'] . 'small-' . $creatTime . ".";
                $ext = pathinfo($data['img'], PATHINFO_EXTENSION);
                $image->thumb(150, 150)->save("./Public/helpImg/" . $smallImgTop . $ext);
                $data["sm_img"] = $smallImgTop . $ext;
                $shopArr = $data;
                $help->add($shopArr);
                redirect("helpOld/id/".$data['uid']);
            }
        }
    }

    //医生列表
    public function mingyi()
    {
        $this->display();
    }

    //会员页面
    public function reg()
    {
        $this->display();
    }

    //注册会员提交
    public function regPost()
    {
        $data = I("post.");
        $user = M("user_main");
        $uid = $user->add($data);

        $appid = "wx979809bd806bc203";
        $uri = "http://old.dici.xin/index.php/Home/Index/orders";
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid
            . "&redirect_uri=" . $uri .
            "&response_type=code&scope=snsapi_userinfo&state=" . $uid . "&connect_redirect=1#wechat_redirect";
        $this->success("注册成功", $url);
    }

    //注册成功页面
    public function regSuccess()
    {
        $code = $_GET['code'];
        $uid = $_GET['state'];
        $info = self::getWechatInfo($code);//微信用户信息
        $wx = M("user_wx");
        $userWx = $wx->where("openid='" . $info['openid'] . "'")->find();
        if (empty($userWx)) {
            //没有openid,没有注册
            $data['openid'] = $info['openid'];
            $data['uid'] = $uid;
            $wx->add($data);
            redirect("/orders/id/" . $uid);
        } else {
            redirect("/orders/id/" . $userWx['uid']);
        }
    }

    //订单页面
    public function orders()
    {
        $order = M("order_info");
        $code = $_GET['code'];
        $uid = $_GET['state'];
        $info = self::getWechatInfo($code);//微信用户信息
        $wx = M("user_wx");
        $userWx = $wx->where("openid='" . $info['openid'] . "'")->find();
        if ($uid == 'STATE') {//没有uid参数
            if (empty($userWx)) {
                //没有openid,注册
                redirect("reg");
            } else {//有openid,已经注册
                $datas = $order->where("uid=" . $userWx['uid'])->select();
                $this->assign("datas", $datas);
                $this->display();
            }
        } else {
            //添加ｏｐｅｎｉｄ
            $data['openid'] = $info['openid'];
            $data['uid'] = $uid;
            $wx->add($data);

            $datas = $order->where("uid=" . $uid)->select();
            $this->assign("datas", $datas);
            $this->display();
        }
    }

    /*
    * 获取微信网页操作等
    * @wxj
    * */
    public static function getWechatInfo($code)
    {
        $appid = "wx979809bd806bc203";
        $secret = "9c043fd8759eab0c0e56ffb85534a4ce";
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid .
            "&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
        $res = curl_get($url);//微信code换取网页授权token
        $rsArr = json_decode($res, true);
        $infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" .
            $rsArr['access_token'] . "&openid=" . $rsArr['openid'] . "&lang=zh_CN";
        $infoRs = curl_get($infoUrl);//拉取用户信息
        $infoRsArr = json_decode($infoRs, true);
        return $infoRsArr;
    }

    //老年学院
    public
    function oldSchool()
    {
        $this->display();
    }

    //会员详情页
    public
    function vipDetail()
    {
        $this->display();
    }

    //才艺详情
    public
    function artDetail()
    {
        $this->display();
    }

    //旅游详情
    public
    function traDetail($id)
    {
        $tra = M("travel_info");
        $data = $tra->where("tid=" . $id)->find();
        $this->assign("data", $data);
        $this->display();
    }

    //52详情
    public
    function clazzDetail()
    {
        $this->display();
    }

    //支付页
    public function payOrder($id)
    {
        vendor('wxPayApi.example.log');
        vendor('wxPayApi.lib.WxPay#Api');
        vendor('wxPayApi.example.WxPay#JsApiPay');
        //初始化日志
        $logHandler = new \CLogFileHandler("../logs/" . date('Y-m-d') . '.log');
        $log = \Log::Init($logHandler, 15);
        //①、获取用户openid
        $tools = new \JsApiPay();
        $openId = $tools->GetOpenid();
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("bamahenda");
        $input->SetAttach("bamahenda");
        $input->SetOut_trade_no(\WxPayConfig::MCHID . date("YmdHis"));
        $input->SetTotal_fee($id * 100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("bamahenda");
        $input->SetNotify_url("notify.php");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        //获取共享收货地址js函数参数
//        $editAddress = $tools->GetEditAddressParameters();
        $this->assign("jsApiParameters", $jsApiParameters);
//        $this->assign("editAddress",$editAddress);
        $this->assign("money", $id);
        $this->display();
    }

    //获得金额
    public function getMoney()
    {
        $postData = I("post.");
        $appid = "wx979809bd806bc203";
        $uri = "http://old.dici.xin/index.php/Home/Index/isReg";
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid
            . "&redirect_uri=" . $uri .
            "&response_type=code&scope=snsapi_userinfo&state=" . $postData['money'] . "&connect_redirect=1#wechat_redirect";
        redirect($url);//发起请求
    }

    //判断是否注册
    public function isReg()
    {
        $code = $_GET['code'];
        $money = $_GET['state'];
        $info = self::getWechatInfo($code);//微信用户信息
        $wx = M("user_wx");
        $userWx = $wx->where("openid='" . $info['openid'] . "'")->find();
        if (empty($userWx)) {
            //没有openid,注册
            redirect("reg");
        } else {//有openid,已经注册
            redirect("http://old.dici.xin/index.php/Home/Index/payOrder/id/" . $money);
        }
    }
    //判断是否能够发布互助的帖子
    public function isHelp(){
        $code = $_GET['code'];
        $info = self::getWechatInfo($code);//微信用户信息
        $wx = M("user_wx");
        $userWx = $wx->where("openid='" . $info['openid'] . "'")->find();
        if (empty($userWx)) {
            //没有openid,注册
            redirect("reg");
        } else {//有openid,已经注册
            redirect("http://old.dici.xin/index.php/Home/Index/addHelp/id/".$userWx['uid']);
        }
    }


    //查看支付回调
    public function notify()
    {
        vendor('wxPayApi.example.log');
        vendor('wxPayApi.lib.WxPay#Api');
        vendor('wxPayApi.lib.WxPay#Notify');

        //初始化日志
        $logHandler = new CLogFileHandler("../logs/" . date('Y-m-d') . '.log');
        $log = Log::Init($logHandler, 15);

    }


}